package com.xiaoli.service.impl;

import com.xiaoli.constant.MessageConstant;
import com.xiaoli.dto.UserDTO;
import com.xiaoli.dto.UserLoginDTO;
import com.xiaoli.entity.User;
import com.xiaoli.exception.PasswordErrorException;
import com.xiaoli.exception.UserNotFoundException;
import com.xiaoli.exception.UsernameDuplicatedException;
import com.xiaoli.mapper.UserMapper;
import com.xiaoli.service.UserService;
import com.xiaoli.vo.UserInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Override
    public User getByUserName(String userName) {
        return userMapper.getByUserName(userName);
    }

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {
        String userName = userLoginDTO.getUserName();
        String password = userLoginDTO.getPassword();

        User user = userMapper.getByUserName(userName);
        //用户不存在
        if(user == null){
            throw new UserNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码错误
        if(!password.equals(user.getPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        return user;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public void register(User user) {
        //获取用户名
        String name = user.getUserName();
        //查询是否存在用户
        User resultUser = userMapper.getByUserName(name);
        // 判断结果集是否为空
        if(resultUser != null){
            // 抛出异常
            throw new UsernameDuplicatedException(MessageConstant.ACCOUNT_DUPLICATED);
        }
        userMapper.insert(user);
    }
    @Override
    public UserInfoVO getById(int userId) {
        User user = userMapper.getById(userId);
        if(user == null){
            throw new UserNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user,userInfoVO);
        return userInfoVO;
    }

    /**
     * 用户信息更新
     * @param userDTO
     */
    @Override
    public void update(UserDTO userDTO) {
          return;
    }
}
